package com.xiaowu.netmusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.xiaowu.netmusic.domain.po.LoginUser;
import com.xiaowu.netmusic.domain.po.UserPO;
import com.xiaowu.netmusic.mapper.UserMapper;
import com.xiaowu.netmusic.utils.LoginTypeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * @description:
 * @author: xiaowu
 * @time: 2024/12/23 14:48
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true) // 补充：读-only事务，保障性能、避免误写
public class UserDetailServiceImpl implements UserDetailsService {

    private final UserMapper userMapper; // final字段，@RequiredArgsConstructor 自动注入

    /**
     * 核心认证方法：通过用户名查询用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String loginInput) throws UsernameNotFoundException {
        if (!StringUtils.hasText(loginInput)) {
            log.warn("登录失败，输入为空");
            throw new UsernameNotFoundException("登录名不能为空");
        }

        LambdaQueryWrapper<UserPO> queryWrapper = new LambdaQueryWrapper<>();

        // 简单判断 loginInput 的类型
        if (LoginTypeUtil.isEmail(loginInput)) {
            // 是邮箱
            queryWrapper.eq(UserPO::getEmail, loginInput);
        } else if (LoginTypeUtil.isPhoneNumber(loginInput)) {
            // 是手机号
            queryWrapper.eq(UserPO::getPhone, loginInput);
        } else {
            // 默认按照用户名
            queryWrapper.eq(UserPO::getUsername, loginInput);
        }

        UserPO user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            log.warn("登录失败，未找到用户: {}", loginInput);
            throw new UsernameNotFoundException("账号不存在: " + loginInput);
        }

        return new LoginUser(user);
    }
}
